package com.movie.music;

import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.movie.R;

import java.util.List;

/**
 * Created by syf on 2019/3/30.
 */

public class MusicAdapter extends ArrayAdapter {
    Context context;
    public Song selSong;
    int resourceId;
    private List<Song> songList;

    public MusicAdapter(Context context, int resource, List<Song> objects) {
        super(context, resource, objects);
        this.context = context;
        this.resourceId = resource;
        this.songList = objects;
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Song song = (Song) getItem(position); // 获取当前项的Fruit实例
        View view = LayoutInflater.from(getContext()).inflate(resourceId, null);//实例化一个对象
        //ImageView fruitImage = (ImageView) view.findViewById(R.id.fruit_image);//获取该布局内的图片视图
        TextView musicName = (TextView) view.findViewById(R.id.music_name);//获取该布局内的文本视图
        //fruitImage.setImageResource(fruit.getImageId());//为图片视图设置图片资源
        musicName.setText(song.getTitle());//为文本视图设置文本内容

        TextView artist = (TextView) view.findViewById(R.id.artist);//获取该布局内的文本视图
        //fruitImage.setImageResource(fruit.getImageId());//为图片视图设置图片资源
        artist.setText(song.getArtist());//为文本视图设置文本内容

        RadioButton radioBtn = (RadioButton) view
                .findViewById(R.id.radioButton);
        radioBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                select(position);

            }

        });
        //radioBtn.setClickable(song.getSelected());
        radioBtn.setChecked(song.getSelected());
        return view;
    }
    // 选中当前选项时，让其他选项不被选中
    public void select(int position) {
        if (!songList.get(position).isSelected()) {
            songList.get(position).setSelected(true);
            selSong =  songList.get(position);
            for (int i = 0; i < songList.size(); i++) {
                if (i != position) {
                    songList.get(i).setSelected(false);
                }
            }
        }
        notifyDataSetChanged();
    }
}
